package com.simen.hellobytes.encrypt;

import com.simen.hellobytes.exception.EncryptException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.CRC32;

/**
 * @author Created by Simen.
 * @date 创建日期 2018/8/31 11:25
 * @modify 修改者 Simen
 */
public class CRC32Util {

    public static long getCRC32(byte[] data) {
        CRC32 crc32 = new CRC32();

        crc32.update(data);

        return crc32.getValue();
    }

    public static long getCRC32(File file) throws EncryptException {
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);

            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());

            CRC32 crc32 = new CRC32();

            crc32.update(byteBuffer);

            return crc32.getValue();
        } catch (Exception e) {
            throw new EncryptException(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
